package com.example.tripos;
 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

public class MainActivity extends Activity implements OnClickListener {

	ImageView pic, button;
	Facebook fb;
	SharedPreferences sp;
	


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		String facebook_app_id = getString(R.string.facebook_app_id);
		fb = new Facebook(facebook_app_id);
		
		
		sp = getPreferences(MODE_PRIVATE);
		
		String access_token = sp.getString("access_token", null);
		long expires = sp.getLong("access_expires", 0);
		
		
		if(access_token != null){
			fb.setAccessToken(access_token);
		}
		if(expires != 0){
			fb.setAccessExpires(expires);
		}
			
			
		
		pic=(ImageView)findViewById(R.id.picture_login);
		button=(ImageView)findViewById(R.id.login);
		button.setOnClickListener(this);
		updateLoginImageButton();
		
	}

	private void updateLoginImageButton() {
		// TODO Auto-generated method stub
		if(fb.isSessionValid())//show logout button
		{
			
			button.setImageResource(R.drawable.logout);
			
			pic.setVisibility(ImageView.INVISIBLE);
			
			JSONObject obj = null;
			URL img_url = null;
			
			
			try {
				String jsonUser = fb.request("me");
				obj= Util.parseJson(jsonUser);
				
				String user_id = obj.optString("id");
				String user_name = obj.optString("name");
				
				img_url = new URL("http://graph.facebook.com/"+user_id+"/picture?type=normal");
				Bitmap map = BitmapFactory.decodeStream(img_url.openConnection().getInputStream());
				
				pic.setImageBitmap(map);
				
			} catch (FacebookError e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
			
			
		}else{//show login button
			button.setImageResource(R.drawable.login);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(fb.isSessionValid()){ //connected, log out
			try {
				fb.logout(getApplicationContext());
				updateLoginImageButton();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else{//log in to facebook
			fb.authorize(this, new String[] {"email"} ,new DialogListener() 
			{
				
				@Override
				public void onFacebookError(FacebookError e) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onError(DialogError e) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onComplete(Bundle values) {
					// TODO Auto-generated method stub
					Editor editor = sp.edit();
					editor.putString("access_token", fb.getAccessToken());
					editor.putLong("access_expires" , fb.getAccessExpires());
					
					updateLoginImageButton();
				}
				
				@Override
				public void onCancel() {
					// TODO Auto-generated method stub
					Toast.makeText(MainActivity.this, "On Cancel", Toast.LENGTH_SHORT).show();
				}
			});
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		fb.authorizeCallback(requestCode, resultCode, data);
	}
}
